package router

import (
	"github.com/gin-gonic/gin"
	"github.com/honwee/awm/internal/api/handler"
	"github.com/honwee/awm/internal/api/middleware"
	"github.com/honwee/awm/internal/service"
	"github.com/honwee/awm/pkg/logger"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
)

type Router struct {
	engine             *gin.Engine
	traceHandler       *handler.TraceHandler
	workflowRunHandler *handler.WorkflowRunHandler
	projectUserHandler *handler.ProjectUserHandler
	authMiddleware     *middleware.AuthMiddleware
	log                *zap.SugaredLogger
}

func NewRouter(engine *gin.Engine, traceService *service.TraceService, workflowRunService *service.WorkflowRunService, projectUserService *service.ProjectUserService) *Router {
	return &Router{
		engine:             engine,
		traceHandler:       handler.NewTraceHandler(traceService),
		workflowRunHandler: handler.NewWorkflowRunHandler(workflowRunService),
		projectUserHandler: handler.NewProjectUserHandler(projectUserService),
		authMiddleware:     middleware.NewAuthMiddleware(projectUserService),
		log:                logger.Logger.Sugar(),
	}
}

func (r *Router) Setup() {
	// 使用中间件
	r.engine.Use(middleware.Logger())
	r.engine.Use(middleware.ErrorHandler())
	r.engine.Use(gin.Recovery())

	// API路由
	apiV1 := r.engine.Group("/api/v1")
	{
		// 项目用户管理 - 不需要认证的接口
		projectUsers := apiV1.Group("/project-users")
		{
			projectUsers.POST("", r.projectUserHandler.CreateProjectUser)
		}

		// API Key管理 - 不需要认证的接口
		apiKeys := apiV1.Group("/api-keys")
		{
			apiKeys.POST("/generate", r.projectUserHandler.GenerateAPIKey)
		}

		// 需要认证的路由组
		auth := apiV1.Group("")
		auth.Use(r.authMiddleware.APIKeyAuth())
		{
			traces := auth.Group("/traces")
			{
				traces.GET("/workflow/:workflow_id", r.traceHandler.GetWorkflowTraces)
				traces.GET("/workflow-run/:workflow_run_id", r.traceHandler.GetWorkflowRunTraces)
				traces.GET("/node-run/:node_run_id", r.traceHandler.GetNodeRunTraces)
				traces.GET("/node/:node_id", r.traceHandler.GetNodeTraces)
				traces.GET("/event/:event", r.traceHandler.GetTracesByEvent)
			}

			workflowRuns := auth.Group("/workflow-runs")
			{
				workflowRuns.POST("", r.workflowRunHandler.CreateWorkflowRun)
				workflowRuns.PUT("/:workflow_run_id", r.workflowRunHandler.UpdateWorkflowRun)
				workflowRuns.GET("/:workflow_run_id", r.workflowRunHandler.GetWorkflowRun)
				workflowRuns.GET("/user/:user_id", r.workflowRunHandler.GetUserWorkflowRuns)
				workflowRuns.GET("/status/:status", r.workflowRunHandler.GetWorkflowRunsByStatus)
				workflowRuns.GET("/workflow/:workflow_id", r.workflowRunHandler.GetWorkflowRuns)
			}

			// API Key管理 - 需要认证的接口
			apiKeys := auth.Group("/api-keys")
			{
				apiKeys.DELETE("/:user_id", r.projectUserHandler.DeleteAPIKey)
				apiKeys.POST("/:user_id/regenerate", r.projectUserHandler.RegenerateAPIKey)
			}
		}
	}

	// Swagger文档
	r.engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
